package org.fujie.plugin.cloud.face.tencent.convert;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.StrUtil;
import com.tencentcloudapi.ocr.v20181119.models.IDCardOCRResponse;
import org.fujie.plugin.cloud.core.model.RecognizedIdCardScanRes;

import java.time.format.DateTimeParseException;
import java.util.List;
import java.util.Optional;

/**
 * @author slm
 * @description
 */
public class TencentConvert {

    /**
     * @param ocrResponse 腾讯ocr响应
     * @param type        0:人像面，1:国徽面
     * @return RecognizedIdCardScanRes 身份证识别统一返回结构
     * @author sunliming
     * @description
     */
    public static RecognizedIdCardScanRes ofRes(IDCardOCRResponse ocrResponse, int type) {

        RecognizedIdCardScanRes idCardScanRes = new RecognizedIdCardScanRes();
        if(0==type){

            idCardScanRes.setCertName(ocrResponse.getName());
            idCardScanRes.setCertNo(ocrResponse.getIdNum());
            idCardScanRes.setSex(ocrResponse.getSex());
            idCardScanRes.setEthnicity(ocrResponse.getNation());
            idCardScanRes.setBirthDate(ocrResponse.getBirth());
            idCardScanRes.setAddress(ocrResponse.getAddress());
        } else if (1==type) {

            idCardScanRes.setIssueAuthority(ocrResponse.getAuthority());
            idCardScanRes.setValidPeriod(ocrResponse.getValidDate());

            List<String> dateList = StrUtil.splitTrim(ocrResponse.getValidDate(), "-")
                    .stream()
                    .map(s -> {
                        if (CharSequenceUtil.equalsIgnoreCase("长期", s)) {
                            return Optional.of(s);
                        } else {
                            try {
                                String formattedDate = LocalDateTimeUtil.format(LocalDateTimeUtil.parse(s, "yyyy.mm.dd"), DatePattern.PURE_DATE_PATTERN);
                                return Optional.of(formattedDate);
                            } catch (DateTimeParseException e) {
                                return Optional.<String>empty();
                            }
                        }
                    })
                    .flatMap(Optional::stream)
                    .toList();

            if (dateList.size() == 2) {
                idCardScanRes.setStartDate(dateList.get(0));
                idCardScanRes.setEndDate(dateList.get(1));
            }
        }
        return idCardScanRes;
    }
}
